<template>
  <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
    <a-form :form="form" @submit="handleSubmit">

      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="角色名称"
        hasFeedback
      >
        <a-input
          placeholder="角色名称"
          v-decorator="[ 'name', rules.name ]"
        ></a-input>
      </a-form-item>

      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="是否启用"
        hasFeedback
      >
        <a-select v-decorator="['availableStatus', {rules: [{ required: true, message: '请选择状态' }], initialValue: 1}]">
          <a-select-option :value="1">启用</a-select-option>
          <a-select-option :value="0">禁用</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="描述"
        hasFeedback
        help="请填写一段描述"
      >
        <a-textarea :rows="5" placeholder="..."  v-decorator="['remark']"/>
      </a-form-item>

      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="菜单权限"
      >
        <a-tree
          v-model="checkedKeys"
          checkable
          :treeData="menuData"
          :expandedKeys="expandedKeys"
        >

        </a-tree>
      </a-form-item>

      <a-form-item
        v-bind="buttonCol"
      >
        <a-row>
          <a-col span="6">
            <a-button type="primary" html-type="submit">提交</a-button>
          </a-col>
          <a-col span="10">
            <a-button @click="handleGoBack">返回</a-button>
          </a-col>
          <a-col span="8"></a-col>
        </a-row>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import {saveRole, getRoleDetail, getMenuList} from "../../api/auth";
import { require, number } from '../../utils/rules';
import pick from 'lodash.pick'

export default {
  name: 'RoleDetail',
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      },
      buttonCol: {
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12, offset: 5 }
        }
      },
      form: this.$form.createForm(this),
      id: 0,
      menuData: [],
      expandedKeys: [],
      checkedKeys:[],
      rules: {
        name: {rules:[require("请输入角色名称")]},
      },
    }
  },
  async mounted () {
      await this.loadMenu()
      this.loadData()
  },
  methods: {
    handleGoBack() {this.$router.push({name: 'RoleList'})},
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields(async (err, values) => {
        if (!err) {
          let fillUpMenuId = this.fillUpMenu();
          console.log('[fillUpMenuId]',fillUpMenuId);
          let resp = await saveRole({adminRole: Object.assign({id: this.id},values), menuIds: fillUpMenuId})
          if (this.validResp(resp)) {
            this.$message.success(resp.msg);
            this.$router.push({name: 'RoleList'});
          }
        }
      })
    },
    fillUpMenu () {
      let fillUpMenuIds = []
      let checkedMenus = this.flatMenuToArray(this.menuData) 
      checkedMenus.forEach(item => {
        let ids = item.nodePath.split('/');
        if (ids != null && ids.length > 0) {
          ids.filter(id => id != null && id != '' && fillUpMenuIds.indexOf(id) === -1)
          .map(id => fillUpMenuIds.push(id));
        }
      })
      return fillUpMenuIds;
    },
    flatMenuToArray (list) {
      let menus = []
      list.forEach(item => {
        if(this.checkedKeys.some(menuId => menuId == item.key) ) {
          menus.push(item)
        }
        if(item.children && item.children.length > 0) menus = menus.concat(this.flatMenuToArray(item.children))
      })
      return menus
    },
    async loadMenu() {
      let resp = await getMenuList();
      if (this.validResp(resp)) {
        let menuList =  this.initMenu(resp.data.dataList)
        this.menuData = [...menuList]
        console.log('[menuData]',this.menuData);
        
      }
    },
    initMenu(menus) {
      let newMenus = []
      menus.map(item => {
        item.isLeaf = item.isLeaf == 0 ? false: true;
        item.title = item.name
        item.key = item.id
        if (item.children) {
          this.expandedKeys.push(item.key)
          item.children = this.initMenu(item.children)
        }
        newMenus.push(pick(item, ['isLeaf','title','key','children','nodePath']))
      })
      return newMenus;
    },
    async loadData (data) {
      const { form } = this
      let id = this.$route.query.id || 0
      if (id > 0) {
        this.id  = id
        let resp = await getRoleDetail({id: id})
        if (this.validResp(resp)) {
          // this.pageTitle = "编辑用户"
          this.isEdit = true
          this.checkedKeys = [...resp.data.adminRole.menuIds]

          let formData = pick(resp.data.adminRole, ['name','availableStatus','remark'])
          form.setFieldsValue(formData)
        }
      } else {
        this.isEdit = false
      }
    }
  }
}
</script>
